package com.mumu.xiaodu

import android.content.Context
import android.content.SharedPreferences
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import kotlinx.coroutines.*
import android.os.Handler
import android.os.Looper

data class Bookmark(
    val title: String,
    val url: String,
    val category: String,
    val id: Long = System.currentTimeMillis()
)

class BookmarkManager(private val context: Context) {
    
    private val prefs: SharedPreferences = context.getSharedPreferences("bookmarks", Context.MODE_PRIVATE)
    private val gson = Gson()
    
    // 🚀 后台线程处理器，避免 StrictMode 违规
    private val bookmarkScope = CoroutineScope(Dispatchers.IO + SupervisorJob())
    
    fun getAllBookmarks(): List<Bookmark> {
        val json = prefs.getString("bookmarks_list", "[]")
        val type = object : TypeToken<List<Bookmark>>() {}.type
        return gson.fromJson(json, type) ?: emptyList()
    }
    
    fun getBookmarksByCategory(category: String): List<Bookmark> {
        return getAllBookmarks().filter { it.category == category }
    }
    
    // 🚀 异步添加书签，避免主线程磁盘操作
    fun addBookmark(bookmark: Bookmark) {
        bookmarkScope.launch {
            try {
                val bookmarks = withContext(Dispatchers.IO) {
                    getAllBookmarks().toMutableList()
                }
                
                // 检查是否已存在相同URL的书签
                val existingIndex = bookmarks.indexOfFirst { it.url == bookmark.url }
                if (existingIndex != -1) {
                    // 更新现有书签
                    bookmarks[existingIndex] = bookmark
                } else {
                    // 添加新书签
                    bookmarks.add(bookmark)
                }
                
                withContext(Dispatchers.IO) {
                    saveBookmarks(bookmarks)
                }
            } catch (e: Exception) {
                android.util.Log.w("BookmarkManager", "Failed to save bookmark: ${e.message}")
            }
        }
    }
    
    // 🚀 异步删除书签
    fun removeBookmark(bookmarkId: Long) {
        bookmarkScope.launch {
            try {
                val bookmarks = withContext(Dispatchers.IO) {
                    getAllBookmarks().toMutableList()
                }
                bookmarks.removeAll { it.id == bookmarkId }
                
                withContext(Dispatchers.IO) {
                    saveBookmarks(bookmarks)
                }
            } catch (e: Exception) {
                android.util.Log.w("BookmarkManager", "Failed to remove bookmark: ${e.message}")
            }
        }
    }
    
    // 🚀 异步更新书签
    fun updateBookmark(bookmark: Bookmark) {
        bookmarkScope.launch {
            try {
                val bookmarks = withContext(Dispatchers.IO) {
                    getAllBookmarks().toMutableList()
                }
                val index = bookmarks.indexOfFirst { it.id == bookmark.id }
                if (index != -1) {
                    bookmarks[index] = bookmark
                    withContext(Dispatchers.IO) {
                        saveBookmarks(bookmarks)
                    }
                }
            } catch (e: Exception) {
                android.util.Log.w("BookmarkManager", "Failed to update bookmark: ${e.message}")
            }
        }
    }

    fun isBookmarked(url: String): Boolean {
        return getAllBookmarks().any { it.url == url }
    }

    fun getBookmarkByUrl(url: String): Bookmark? {
        return getAllBookmarks().find { it.url == url }
    }

    fun searchBookmarks(query: String): List<Bookmark> {
        return getAllBookmarks().filter { 
            it.title.contains(query, ignoreCase = true) || 
            it.url.contains(query, ignoreCase = true) 
        }
    }

    fun getCategories(): List<String> {
        return getAllBookmarks().map { it.category }.distinct().sorted()
    }

    private fun saveBookmarks(bookmarks: List<Bookmark>) {
        val json = gson.toJson(bookmarks)
        prefs.edit().putString("bookmarks_list", json).apply()
    }
    
    // 🧹 清理资源
    fun cleanup() {
        bookmarkScope.cancel()
    }
} 